<template>
  <PageContainer>
    <view class="container hb-min-h-screen hb-bg-white">
      <Header
        title=""
        :is-custom-back="isFromStartPage || isBackHome"
        @go-back="goBack"
        :is-box-shadow="false"
      />
      <!-- #ifdef MP -->
      <!-- <GetPhoneNumber @nav-back="navBack" /> -->
      <!-- #endif -->
      <TmForm
        v-model="formData"
        :border="false"
        :layout="'horizontal'"
        @submit="loginSubmit"
        :label-width="0"
        :margin="[32, 64]"
        :padding="[0, 0]"
      >
        <TmText label="登录" class="hb-mb-3 hb-flex hb-justify-center" :font-size="48" />
        <TmText
          :label="`登录您的${appStore.appName}账号`"
          class="hb-mb-11 hb-flex hb-justify-center"
          :font-size="28"
        />
        <TmFormItem
          :margin="[0, 0, 0, 0]"
          :padding="[0, 0]"
          field="phoneNumber"
          :rules="[{ required: true, message: '请输入您的手机号' }]"
        >
          <TmInput
            v-model="formData.phoneNumber"
            prefixLabel="手机号"
            placeholder="请输入您的手机号"
            :round="6"
            :input-padding="[32, 0]"
            :height="88"
          ></TmInput>
        </TmFormItem>
        <TmFormItem
          :margin="[0, 0, 0, 24]"
          :padding="[0, 0]"
          field="code"
          :rules="[{ required: true, message: '请输入验证码' }]"
        >
          <view class="hb-flex hb-items-center hb-gap-2">
            <TmInput
              class="hb-flex-1"
              v-model="formData.code"
              prefixLabel="验证码"
              placeholder="请输入验证码"
              :round="6"
              :input-padding="[32, 0, 0, 0]"
              :height="88"
            />
            <TmButton
              :label="codeText"
              :round="6"
              :follow-theme="false"
              color="#F2F3F5"
              font-color="#969799"
              @click="getCode"
            />
          </view>
        </TmFormItem>

        <TmButton
          :loading="loading"
          label="立即登录"
          :margin="[0, 0, 0, 16]"
          form-type="submit"
          :block="true"
          :round="11"
        ></TmButton>
        <!-- #ifdef MP-WEIXIN -->
        <TmButton
          v-if="agreeProtocol"
          label="授权一键登录"
          color="#fff"
          :loading="wxLoading"
          :follow-theme="false"
          :font-color="getThemeColor"
          :border="2"
          :border-color="getThemeColor"
          :block="true"
          :round="11"
          open-type="getPhoneNumber"
          @getphonenumber="getPhoneNumber"
        ></TmButton>
        <TmButton
          v-else
          label="授权一键登录"
          color="#fff"
          :loading="wxLoading"
          :follow-theme="false"
          :font-color="getThemeColor"
          :border="2"
          :border-color="getThemeColor"
          :block="true"
          :round="11"
          @click="modalVisible = true"
        ></TmButton>
        <!-- #endif -->
        <view class="hb-flex hb-items-center hb-mt-4">
          <radio-group @change="agreeProtocol = true">
            <radio
              :value="agreeProtocol"
              :checked="agreeProtocol"
              style="transform: scale(0.7)"
              color="#2878FF"
            />
          </radio-group>
          <text class="hb-text-gray-400 hb-text-xs" @click="agreeProtocol = true">
            <text>我已阅读并同意</text>
            <text @click="openProtocol('register')" class="hb-text-primary">《用户注册协议》</text>
            <text>及</text>
            <text @click="openProtocol('privacy')" class="hb-text-primary">《隐私政策》</text>
          </text>
        </view>
      </TmForm>
      <TmModal
        v-model:show="modalVisible"
        title="提示"
        :height="400"
        ok-text="同意"
        @ok="agreeProtocol = true"
      >
        <text class="hb-text-base">
          <text>我已阅读并同意</text>
          <text @click="openProtocol('register')" class="hb-text-primary">《用户注册协议》</text>
          <text>及</text>
          <text @click="openProtocol('privacy')" class="hb-text-primary">《隐私政策》</text>
        </text>
      </TmModal>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* login 登录 */
  import { ThridTypeEnum } from '@/enums/LoginEnum';
  import { LoginPage } from '@/router/types/modules';
  import { Toast } from '@/utils';
  import { useUserStore } from '@/store/modules/user';
  import { useTmpiniaStore } from '@/tmui/tool/lib/tmpinia';
  import { useAppStore } from '@/store/modules/app';
  import { TabbarPageEnum } from '@/enums/PageEnum';
  import { getVerificationCode, phoneNumberApi, wxPhoneCodeLogin } from '@/api/login';
  import { isString } from 'lodash-es';

  const appStore = useAppStore();
  const tmStore = useTmpiniaStore();
  const getThemeColor = computed(() => tmStore.getThemeColor);

  const modalVisible = ref(false);

  const isFromStartPage = ref(false);
  const androidBack = ref(true);
  const isBackHome = ref();
  let success: LoginPage['success'];
  const useUser = useUserStore();
  const agreeProtocol = ref(false); // 是否同意协议

  customOnload<'login'>((op) => {
    success = op.success;
    isBackHome.value = op.isBackHome;
  });

  const formData = reactive({
    phoneNumber: '',
    code: '',
  });
  const loading = ref(false);
  function loginSubmit(e: Tmui.tmFormSubmitResult<any>) {
    if (!e.isPass) return;
    if (!agreeProtocol.value) {
      modalVisible.value = true;
      return;
    }
    loading.value = true;
    wxPhoneCodeLogin({
      phone: formData.phoneNumber,
      verificationCode: formData.code,
      thridType: ThridTypeEnum.MINIAPP,
    })
      .then(async () => {
        await useUser.getUserInfo();
        navBack();
      })
      .catch(() => (loading.value = false));
  }

  // 打开协议页面
  function openProtocol(type: 'register' | 'privacy') {
    // #ifdef MP-WEIXIN
    if (type === 'privacy') {
      useAppStore()
        .getPrivacySetting()
        .then(() => {
          wx.openPrivacyContract({});
        });
      return;
    }
    // #endif
    // 跳转至协议页面
    navigateTo({
      name: 'userAgreement',
    });
  }

  const defaultCodeText = '获取验证码';
  const codeText = ref(defaultCodeText);
  const codeCountdown = ref<number>(0);
  const codeTimer = ref<NodeJS.Timeout | null>(null);

  const handleCountdown = () => {
    codeCountdown.value--;
    codeText.value = codeCountdown.value.toString();
    if (codeCountdown.value <= 0 && codeTimer.value) {
      resetCode();
    }
  };

  function resetCode() {
    codeCountdown.value = 0;
    codeText.value = defaultCodeText;
    codeTimer.value && clearInterval(codeTimer.value);
    codeTimer.value = null;
  }

  function getCode() {
    if (!formData.phoneNumber) {
      Toast('请输入手机号');
      return;
    }
    if (codeTimer.value) return;
    codeCountdown.value = 60;
    handleCountdown();
    codeTimer.value = setInterval(handleCountdown, 1000);
    getVerificationCode({ phone: formData.phoneNumber, thridType: ThridTypeEnum.MINIAPP })
      .then((res) => {
        Toast('获取验证码成功');
        if (isString(res) && res.includes('验证码已发送，请注意查收')) {
          formData.code = res.replace(/[^\d]/g, '');
        }
      })
      .catch(() => {
        resetCode();
      });
  }

  const wxLoading = ref(false);
  function getPhoneNumber({ detail: { code, iv, encryptedData, errno } }: any) {
    if (wxLoading.value) return;
    if (errno === 1400001) {
      Toast('手机号快捷登录受限,请联系管理员处理');
      return;
    }
    if (!iv || !encryptedData) return;
    wxLoading.value = true;
    phoneNumberApi({ code, iv, encryptedData, thridType: ThridTypeEnum.MINIAPP })
      .then(async () => {
        await useUser.getUserInfo();
        navBack();
      })
      .catch(() => {
        wxLoading.value = false;
      });
  }

  function goBack() {
    androidBack.value = false;
    switchTab(TabbarPageEnum.BASE_HOME);
  }

  function navBack() {
    androidBack.value = false;
    success?.();
    navigateBack();
  }

  onUnload(() => {
    if (androidBack.value && isBackHome.value) goBack();
  });
</script>

<style lang="scss" scoped></style>
